package interrupt;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class InterruptDemo {
    public static void main(String[] args) throws Exception {
        Object lock = new Object();
        Thread t1 = new Thread(
                () -> {
                    synchronized (lock) {
                        log.info("very lucky");
                        // sleep一会儿
                        try {
                            Thread.sleep(5 * 1000L);
                            log.info("sleep end.");

                        } catch (InterruptedException e) {
                            // JVM 发现中断标志为 true，wait() 会抛出 InterruptedException，
                            // 代码进入 catch 块,中断标志也会被清掉（Thread.isInterrupted() 返回 false）
                            Thread ct = Thread.currentThread();
                            log.info("interrupted? {}", ct.isInterrupted());
                        }
                    }
                }
        );

        Thread t2 = new Thread(
                () -> {
                    log.info("try to get lock for t2");
                    synchronized (lock) {
                        log.info("so luck!");
                        try {
                            Thread.sleep(2000 * 1000L);
                        } catch (InterruptedException e) {
                            log.info("t2 was interrupted:{}", e);
                        }
                        log.info(">>>t2.state:{}", Thread.currentThread().getState());
                    }
                }
        );
        t1.start();
        t2.start();
        Thread.sleep(1_000);          // 确保 t1 先拿到锁
        log.info("t2 state before interrupt: {}", t2.getState()); // BLOCKED
        t2.interrupt();
        log.info("t2 state after interrupt:  {}", t2.getState()); // 仍是 BLOCKED
        t1.join();
        t2.join();
    }
}
